﻿<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>事件绑定</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        list-style: none;
        font-family: "微软雅黑", "张海山锐线体简";
      }
    </style>
  </head>

  <body>
    <input type="button" value="按钮" id="btn1" />
    <script type="text/javascript">
      var oBtn = document.getElementById("btn1");
      addEvent(oBtn, "click", show);
      addEvent(oBtn, "click", show2);
      // removeEvent(oBtn, "click", show);

      //对象.addEventListener(事件名,函数,false);	for 高
      //事件名	onclick	over/out/down/up.........不带on
      //函数	obj.onclick=show	show==函数
      function addEvent(obj, eve, fn) {
        if (obj.addEventListener) {
          obj.addEventListener(eve, fn, false); //由于事件参数不带on
        } else {
          obj.attachEvent("on" + eve, fn); //所以这里的绑定事件要将on补上
        }
      }

      //解绑
      //对象.removeEventListener(事件名,函数,false);  chrome FF IE 9 10
      //对象.detachEvent(事件名,函数);        IE 6 7 8
      // oBtn.detachEvent('onclick',show2);
      //移除函数
      function removeEvent(obj, eve, fn) {
        if (obj.removeEventListener) {
          obj.removeEventListener(eve, fn, false);
        } else {
          obj.detachEvent("on" + eve, fn);
        }
      }

      function show() {
        alert("我将弹出1");
      }

      function show2() {
        alert("我将弹出2");
      }

      function _addEvent(obj, type, fn) {
        if (obj.attachEvent) {
          //在dom对象下添加<'e' + type + fn>属性，并将fn赋值
          obj["e" + type + fn] = fn;
          // 给dom兑现的<type + fn>属性赋值一个匿名函数
          obj[type + fn] = function() {
            obj["e" + type + fn](window.event);
          };
          obj.attachEvent("on" + type, obj[type + fn]);
        } else obj.addEventListener(type, fn, false);
      }

      function _removeEvent(obj, type, fn) {
        if (obj.detachEvent) {
          obj.detachEvent("on" + type, obj[type + fn]);
          obj[type + fn] = null;
        } else obj.removeEventListener(type, fn, false);
      }
    </script>
  </body>
</html>
